<?php
// +----------------------------------------------------------------------
// | 简易CMS
// +----------------------------------------------------------------------
// | Copyright (C) 2010 Hoping Software Studio.
// +----------------------------------------------------------------------
// | Version $Id$
// +----------------------------------------------------------------------
namespace app\home\controller;

/**
 * @package 简易CMS
 * @category 固定内容前台控制模板
 */
class Article extends HomeController {
    /**
     * 前台文章浏览模块
     */
    function View() {
        $model        = model('ArticleTitle');
        $cates        = model('Categories')->lists();
        $customfields = model('Customfields')->lists();
        $tophtml      = $bottomhtml   = '';
        $aid          = input('aid', 0, 'intval');
        if (!$aid) {
            $this->error('对不起，您没有指定要查看的新闻！');
        }
        $article = $model->find($aid);
        if (!$article) {
            $this->error('对不起，您指定要查看的新闻不存在！');
        }
        $article = $article->toArray();
        $this->assign('catid', $article['catid']);
        if (!IS_ROBOT && !cookie('view_article_' . $aid . '_' . get_client_ip())) {
            $model->where(array('aid'=>$aid))->setinc('viewnum');
            cookie('view_article_' . $aid . '_' . get_client_ip(), 1, 1800);
        }
        $catid          = $_GET ['catid'] = $article ['catid'];

        if (empty($article) || ($article ['status'] == 0 && $article ['uid'] != $this->user['uid'])) {
            $this->error("指定的内容不存在或者您无权查看!");
        }
        $tag              = model('Tags');
        $tags             = $tag->alias('a')
                ->join('__TAGSLIST__ b', 'b.tagid=a.tagid', 'LEFT')->where("a.itemid='$aid' AND a.tagtype='article'")->select();
        $article ['tags'] = $tags;

        $article ['custom'] = array(
            'name'  => '',
            'key'   => array(),
            'value' => array()
        );
        if (!empty($article ['customfieldid'])) {
            $article ['custom'] ['value'] = unserialize($article ['customfieldtext']);
            if ($article ['custom'] ['value']) {
                $fields                      = $customfields [$article ['customfieldid']];
                $article ['custom'] ['name'] = $fields ['name'];
                $article ['custom'] ['key']  = $fields ['customfieldtext'];
                foreach ($article ['custom'] ['value'] as $key => $value) {
                    if ($value) {
                        $cf = $article ['custom'] ['key'] [$key];
                        ProcessCustomField($cf, $value, $tophtml, $bottomhtml);
                    }
                }
                if ($tophtml)
                    $tophtml    = '<table class="customfields">' . $tophtml . '</table>';
                if ($bottomhtml)
                    $bottomhtml = '<table class="customfields">' . $bottomhtml . '</table>';
            }
        }
        $cat = $cates[$catid];
        if ($cat ['upid']) {
            $topcatid = $cat ['upid'];
        } else {
            $topcatid = $catid;
        }
        $this->assign('topcatid', $topcatid);

        $page = max(1, intval(intval(config('paginate.var_page'))));
        if ($page > 1 && $page > $article['contents']) {
            $this->error('对不起，您指定的页面不存在！', 1, url('Article/view', array('aid' => $aid)));
        }
        $model   = model('ArticleContent');
        $content = $model->where("aid='$aid' AND pageorder='$page'")->order('pageorder')->find();
        if (!$content && !$article['fromrss']) {
            $this->error('对不起，您指定的内容不存在！');
        }
        $content = $content->toArray();
        $content ['content'] = $tophtml . $content ['content'] . $bottomhtml;
        $pager               = new \CMS\Pager($article['contents'], 1);
        $this->assign('multi', $pager->show());
        //该分类下最新发布的文章
        $where               = "a.aid!='$aid' AND a.catid='$catid'";
        $order               = "a.aid DESC";
        $model               = $model->table('__ARTICLE_TITLE__')->alias('a');
        $article ['related'] = $model->where($where)->order($order)->limit(0, 8)->select();
        // 读取评论，后台设置评论开关，是否本地评论
        // TODO: 评论要做成插件形式
        if (config('LOCAL_COMMENT')) {
            $article ['allowcomment'] = !empty($cat ['allowcomment']) && !empty($article ['allowcomment']) ? 1 : 0;
            $comment_url              = '';
            $depth                    = 1;
            $commentlist              = array();
            if ($article ['allowcomment']) {
                $cmodel   = model('Comment');
                $form_url = url('Comment/manage');
                if ($article ['commentnum'] > 0) {
                    if ($article['commentnum'] > 10)
                        $comment_url = url('Comment/Show', array('aid' => $aid));
                    $cids        = array();
                    //读取评论信息
                    $rows        = $cmodel->where("aid='$aid' AND firstcid='0'")->order('cid DESC')->limit(0, 10)->select();
                    foreach ((array) $rows as $value) {
                        if ($value ['status'] == 0 || $value ['uid'] == $this->user['uid'] || $_G ['adminid'] == 1) {
                            $value ['allowop'] = 1;
                            //$value['message'] = $bb->bbcode2html($value['message'], 1);
                            $commentlist []    = $value;
                            $cids[]            = $value['cid'];
                        }
                    }
                    //读取回复信息
                    $cids = dimplode($cids);
                    $rows = $cmodel->where("aid='$aid' AND firstcid IN ($cids)")->order('cid ASC')->select();
                    foreach ((array) $rows as $value) {
                        if ($value ['status'] == 0 || $value ['uid'] == $this->user['uid'] || $_G ['adminid'] == 1) {
                            $value ['allowop'] = 1;
                            //$value['message'] = $bb->bbcode2html($value['message'], 1);
                            $commentlist []    = $value;
                        }
                    }
                    $tree        = new Tree($commentlist, 'cid', 'upcid');
                    $commentlist = $tree->buildTree();
                }
            }
            $this->assign('commentlist', $commentlist);
        }
        // 检查一下本文是否采集回来地，且是否需要读取正文内容
        $article             = array_merge($article, $content);
        //$article = focus_check($article);
        $content ['content'] = $article ['content'];

        /**
         * 读取图片
         */
        $aimgs = array();
        $rows  = model('Attachment')->where("aid='$aid' AND aidtype='article' AND isimage='1'")->select();
        foreach ((array) $rows as $value) {
            if ($value) {
                $basename = basename($value ['url']);
                if ($basename && !strpos($content ['content'], $basename)) {
                    $aimgs [] = $value;
                }
            }
        }
        $this->assign('aimgs', $aimgs);

        // 给投票做个HASH值，避免恶意投票
        $hash   = md5($article ['uid'] . "\t" . $article['dateline']);
        $this->assign('hash', $hash);
        $idtype = 'aid';

        //下一篇和下一篇
        $sql    = "(SELECT aid,title,shorttitle FROM __ARTICLE_TITLE__ WHERE aid < $aid AND catid = $catid ORDER BY aid DESC LIMIT 0,1)
                UNION ALL
                (SELECT aid,title,shorttitle FROM __ARTICLE_TITLE__ WHERE aid > $aid AND catid = $catid ORDER BY aid ASC LIMIT 0,1)";
        $model = model('ArticleTitle');
        $sql = $model->parseTable($sql);
        $result = $model->query($sql);
        $next   = $prev   = array();
        if ($result) {
            if (count($result) == 1) {
                if ($result[0]['aid'] < $aid) {
                    $prev = $result[0];
                } else {
                    $next = $result[0];
                }
            } else {
                $prev = $result[0];
                $next = $result[1];
            }
        }
        $this->pageTitle = $article ['title'] . ($page > 1 ? " ( $page )" : '') . ' - ' . $cat ['catname'];
        $webkeyword    = $article ['keywords'] ? $article ['keywords'] : $article ['title'];
        $webdescription = $article ['summary'] ? $article ['summary'] : $article ['title'];
        $tpl             = $cat ['contenttplname'] ? $cat ['contenttplname'] : 'article/view';
        $tpl             = str_replace('portal/', 'article/', $tpl);
        $a               = array('article', 'webkeyword', 'webdescription', 'prev', 'next', 'content', 'cat');
        foreach ($a as $k) {
            $this->assign($k, $$k);
        }
        $tpl = str_replace('.html', '', $tpl);
        return $this->fetch($tpl);
    }

    /**
     * 分类内容列表
     */
    function Lists() {
        config('SHOW_PAGE_TRACE', true);
        $catid = input('catid', 0, 'intval');
        if (!$catid) {
            $this->error("您没有指定要查看的分类!");
        }
        $this->assign('catid', $catid);
        $cats = model('Categories')->lists();
        if (isset($cats[$catid])) {
            $cat = $cats[$catid];
        } else {
            $this->error("对不起，您指定的分类不存在!");
        }
        $page            = max(1, intval(input(config('paginate.var_page'))));
        $this->pageTitle = $cat ['catname'] . ($page > 1 ? " ($page)" : '');
        $metadescription = empty($cat ['description']) ? $cat ['catname'] : $cat ['description'];
        $metakeywords    = empty($cat ['keyword']) ? $cat ['catname'] : $cat ['keyword'];
        $model           = model('ArticleTitle');

        $count = $model->where('catid=' . $catid)->count();
        //$count = $cat['articles'];
        $this->assign('count', $count);

        $pager = new \CMS\Pager($count, 10);
        $this->assign('multi', $pager->show());

        $this->assign('page', $page);
        $this->assign('metakeywords', $metakeywords);
        $this->assign('metadescription', $metadescription);

        if ($cat ['upid'])
            $topcatid = $cat ['upid'];
        else
            $topcatid = $catid;
        $orderby  = 'dateline DESC';
        if ($cat['ordertype'] == 1) {
            $orderby = 'dateline ASC';
        }
        $this->assign('orderby', $orderby);
        $this->assign('topcatid', $topcatid);
        $tpl = $cat['primaltplname'];
        $tpl = str_replace('.html', '', $tpl);
        return $this->fetch($tpl);
    }

    /**
     * 附件操作
     * @global array $_G
     */
    function Attachment() {
        global $_G;
        $operation = input('r.op');

        $id     = empty($_GET ['id']) ? 0 : intval($_GET ['id']);
        $aid    = empty($_GET ['aid']) ? '' : intval($_GET ['aid']);
        $model  = model('Attachment');
        $attach = $model->find($id);
        if (empty($attach)) {
            $this->error('对不起，您指定的文件不存在！');
        }

        if ($operation == 'delete') {
            if (!$_G ['group'] ['allowmanagearticle'] && $_G ['uid'] != $attach ['uid']) {
                $this->error("对不起，您无权删除此文件！");
            }
            if ($aid) {
                DB::query("UPDATE #__article_title SET pic = '' WHERE aid='$aid'", 'UNBUFFERED');
            }
            $model->delete($id);
            pic_delete($attach ['attachment'], $attach ['thumb'], 0);
            $this->error("指定的文件已经删除!");
        } else {
            $filename = A_DIR . $attach ['attachment'];
            if (!is_readable($filename)) {
                $this->error('您指定的文件无法被删除！');
            }

            $readmod = 2; // read local file's function: 1=fread 2=readfile
            // 3=fpassthru 4=fpassthru+multiple
            $range   = 0;
            if ($readmod == 4 && !empty($_SERVER ['HTTP_RANGE'])) {
                list ( $range ) = explode('-', (str_replace('bytes=', '', $_SERVER ['HTTP_RANGE'])));
            }

            $filesize            = $attach ['filesize'];
            $attach ['filename'] = '"' . (strtolower(CHARSET) == 'utf-8' && strexists($_SERVER ['HTTP_USER_AGENT'], 'MSIE') ? urlencode($attach ['filename']) : $attach ['filename']) . '"';

            header('Date: ' . gmdate('D, d M Y H:i:s', $attach ['dateline']) . ' GMT');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s', $attach ['dateline']) . ' GMT');
            header('Content-Encoding: none');
            header('Content-Disposition: attachment; filename=' . $attach ['filename']);
            header('Content-Type: ' . $attach ['filetype']);
            header('Content-Length: ' . $filesize);

            if ($readmod == 4) {
                header('Accept-Ranges: bytes');
                if (!empty($_SERVER ['HTTP_RANGE'])) {
                    $rangesize = ($filesize - $range) > 0 ? ($filesize - $range) : 0;
                    header('Content-Length: ' . $rangesize);
                    header('HTTP/1.1 206 Partial Content');
                    header('Content-Range: bytes=' . $range . '-' . ($filesize - 1) . '/' . ($filesize));
                }
            }
            getlocalfile($filename, $readmod, $range);
        }
    }

    /**
     * 顶文章
     */
    public function ding() {
        $uid = is_login();
        $id  = input('get.id');
        if (cookie($uid . 'ding' . $id) != '' || cookie($uid . 'cai' . $id) != '') {
            $this->error('你已经对该内容进行过操作！');
        }
        $res = db('ArticleTitle')->where(array('aid' => $id))->setInc('ding', 1);
        if ($res === false) {
            $this->error('操作失败');
        } else {
            cookie($uid . 'ding' . $id, 1);
            $this->success('操作成功', '', array('id' => 'ding'));
        }
    }

    /**
     * 踩文章
     */
    public function cai() {
        $uid = is_login();
        $id  = input('get.id');
        if (cookie($uid . 'ding' . $id) != '' || cookie($uid . 'cai' . $id) != '') {
            $this->error('你已经对该内容进行过操作！');
        }
        $res = db('ArticleTitle')->where(array('aid' => $id))->setInc('cai', 1);
        if ($res === false) {
            $this->error('操作失败');
        } else {
            cookie($uid . 'cai' . $id, 1);
            $this->success('操作成功', '', array('id' => 'cai'));
        }
    }

}
